<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px" class="advanced-search-form">
      <el-row :gutter="15">
        <!-- 第一行 -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="活动名称" prop="name">
            <el-input
                v-model="queryParams.name"
                placeholder="请输入活动名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="活动类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择活动类型" clearable style="width: 100px">
              <el-option
                  v-for="dict in promotion_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用范围" prop="scope">
            <el-select v-model="queryParams.scope" placeholder="请输入适用范围" clearable style="width: 132px">
              <el-option
                  v-for="dict in promotion_scope"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100px">
              <el-option
                  v-for="dict in promotion_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="15">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="活动时间" prop="timeRange">
            <el-date-picker
                v-model="queryParams.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 250px"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="创建人" prop="createdBy">
            <el-input
                v-model="queryParams.createdBy"
                placeholder="请输入创建人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <!-- 操作按钮 -->
        <el-col :xs="24" :sm="24" :md="16" :lg="12" :xl="12" style="text-align: right; padding-right: 10px;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['transaction:Promotion:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['transaction:Promotion:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['transaction:Promotion:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['transaction:Promotion:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div style="overflow-x: auto;">
      <el-table
          v-loading="loading"
          :data="PromotionList"
          @selection-change="handleSelectionChange"
          style="width: 100%; min-width: 1200px;"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="活动ID" prop="id" align="center" width="100" />
        <el-table-column label="所属门店ID" prop="storeId" align="center" width="120" />
        <el-table-column label="活动名称" prop="name" align="center" width="160" show-overflow-tooltip />
        <el-table-column label="活动类型" align="center" prop="type" width="120">
          <template #default="scope">
            <dict-tag :options="promotion_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="适用范围" align="center" prop="scope" width="110">
          <template #default="scope">
            <dict-tag :options="promotion_scope" :value="scope.row.scope"/>
          </template>
        </el-table-column>
        <el-table-column label="活动时间" align="center" width="220">
          <template #default="scope">
            <div style="display: flex; justify-content: center; align-items: center; gap: 8px;">
              <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
              <span>至</span>
              <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="promotion_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="活动封面图" align="center" prop="bannerUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.bannerUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="活动描述" align="center" prop="description" width="200" show-overflow-tooltip />
        <el-table-column label="创建人" align="center" prop="createdBy" width="120" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="150" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div style="white-space: nowrap;">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['transaction:Promotion:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['transaction:Promotion:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改促销活动管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="PromotionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择活动类型">
            <el-option
                v-for="dict in promotion_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用范围" prop="scope">
          <el-input v-model="form.scope" placeholder="请输入适用范围" />
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
              v-model="form.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
                v-for="dict in promotion_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动封面图" prop="bannerUrl">
          <image-upload v-model="form.bannerUrl"/>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input v-model="form.priority" placeholder="请输入优先级，数值越大优先级越高" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Promotion">
import { listPromotion, getPromotion, delPromotion, addPromotion, updatePromotion } from "@/api/transaction/Promotion"

const { proxy } = getCurrentInstance()
const { promotion_type, promotion_status,promotion_scope } = proxy.useDict('promotion_type', 'promotion_status','promotion_scope')

const PromotionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeId: null,
    name: null,
    type: null,
    scope: null,
    timeRange: null,  // 修改为时间范围
    status: null,
    createdBy: null
  },
  rules: {
    name: [
      { required: true, message: "活动名称不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "活动类型不能为空", trigger: "change" }
    ],
    timeRange: [  // 修改时间验证规则
      { required: true, message: "活动时间不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询促销活动管理列表 */
function getList() {
  loading.value = true
  // 处理时间范围参数
  const params = {
    ...queryParams.value,
    startTime: queryParams.value.timeRange ? queryParams.value.timeRange[0] : null,
    endTime: queryParams.value.timeRange ? queryParams.value.timeRange[1] : null
  }
  delete params.timeRange

  listPromotion(params).then(response => {
    PromotionList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    storeId: null,
    name: null,
    type: null,
    scope: null,
    startTime: null,
    endTime: null,
    timeRange: null,  // 添加时间范围字段
    status: null,
    bannerUrl: null,
    description: null,
    priority: null,
    delFlag: null,
    createTime: null,
    updateTime: null,
    createdBy: null
  }
  proxy.resetForm("PromotionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加促销活动管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPromotion(_id).then(response => {
    form.value = {
      ...response.data,
      timeRange: response.data.startTime && response.data.endTime
          ? [response.data.startTime, response.data.endTime]
          : null
    }
    open.value = true
    title.value = "修改促销活动管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["PromotionRef"].validate(valid => {
    if (valid) {
      // 处理时间范围
      const submitData = {
        ...form.value,
        startTime: form.value.timeRange ? form.value.timeRange[0] : null,
        endTime: form.value.timeRange ? form.value.timeRange[1] : null
      }
      delete submitData.timeRange

      if (form.value.id != null) {
        updatePromotion(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPromotion(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除促销活动管理编号为"' + _ids + '"的数据项？').then(function() {
    return delPromotion(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('transaction/Promotion/export', {
    ...queryParams.value,
    startTime: queryParams.value.timeRange ? queryParams.value.timeRange[0] : null,
    endTime: queryParams.value.timeRange ? queryParams.value.timeRange[1] : null
  }, `Promotion_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.advanced-search-form {
  padding: 18px 10px 0 10px;
  background: #f8f8f8;
  border-radius: 4px;
  margin-bottom: 15px;
}
.advanced-search-form .el-form-item {
  margin-bottom: 15px;
}
</style>